import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;

import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
  

public class MessageReceiverThread extends Thread{
	SynchQueue packetQueue;//<DatagramPacket> 
	SynchQueue  messageQueue; //<Message>
	ObjectInputStream in;
	Message m;
	Object obj;
	
	//receive packet and message SynchQueues
	public MessageReceiverThread(SynchQueue pq, SynchQueue mq){
		packetQueue = pq;
		messageQueue = mq;
	}
	
	
	
	public void run(){
		while(true){
			if(!packetQueue.isEmpty()){
				//dequeue & deserialize
				try {
					//ServerMessage sm = new ServerMonsterMessage(1);
					
					
					Object obj = packetQueue.dequeue();
					DatagramPacket p = (DatagramPacket)obj;
					byte[] by = (byte[])p.getData();
					InputStream bais = new ByteArrayInputStream(by);
					in = new ObjectInputStream(bais);
					
					obj =  in.readObject();
					
					if(obj instanceof ServerMessage){
						messageQueue.enqueue((ServerMessage)obj);
					}
					if(obj instanceof ClientMessage){
						messageQueue.enqueue((ClientMessage)obj);
					}
					
				} catch (IOException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
		        //Object obj = deserialize((Serializable)packetQueue.dequeue());//, Message);
				
			}
		}
	}
	
}

/*http://msdn2.microsoft.com/en-US/library/8z8dy228.aspx
 * 
 * http://javaalmanac.com/egs/java.io/DeserializeObj.html
 */